package validator

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"regexp"
)

// Register 结构体用于接收和验证用户相关参数
type Register struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required,min=6"`
	Mobile   string `json:"mobile" binding:"required"`
}

// 定义验证手机号码的正则表达式
var phoneRegex = regexp.MustCompile(`^1[3-9]\d{9}$`)

var validate *validator.Validate

// 初始化自定义验证规则
func init() {
	validate = validator.New()
	if err := validate.RegisterValidation("validatePhone", validatePhone); err != nil {
		panic(err)
	}
}

// 自定义验证函数，验证手机号码格式是否正确
func validatePhone(fl validator.FieldLevel) bool {
	phone, ok := fl.Field().Interface().(string)
	if !ok {
		return false
	}
	return phoneRegex.MatchString(phone)
}

func Validator(c *gin.Context) error {
	var register Register
	if err := c.ShouldBindJSON(&register); err != nil {
		return err
	}

	if err := validate.Struct(register); err != nil {
		return err
	}

	return nil
}
